/*
This script is used to initialize DB.
User need to change variables as below:
    host_port  :  host and port, such as localhost:22222
    db_name    :  db name, such as "test"
    db_owner   :  db user name
    db_passwd  :  db password 
*/
host_port = "localhost:22002"
db_name = "gate_guard"
db_owner = "dev"
db_passwd = "Aa123456"

function create_all_collections() {
    create_new_collection("account");

    create_new_collection("attendance");
    db.attendance.createIndex({a_mm:-1, u_id:1}, {name:"update", background:true});

    create_new_collection("config");
    create_new_collection("face_feature");
    create_new_collection("ipc");
    create_new_collection("guard");

    create_new_collection("record_stranger");
    db.record_stranger.createIndex({r_at:-1}, {name:"r_at_-1", background:true});
    db.record_stranger.createIndex({d_id:1, r_at:1, track_id:1}, {name:"counting", background:true});

    create_new_collection("record_user");
    db.record_user.createIndex({r_at:-1}, {name:"r_at_-1", background:true});
    db.record_user.createIndex({u_nm:-1,u_tp:1,r_at:-1}, {name:"search", background:true});
    db.record_user.createIndex({u_id:1,r_at:-1}, {name:"attendance", background:true});
    db.record_user.createIndex({d_id:1,r_at:1,u_id:1}, {name:"counting", background:true});

    create_new_collection("user");
    db.user.createIndex({u_dm:1,u_tp:1,u_no:1}, {name:"user_sort", background:true});
    db.user.createIndex({u_tp:-1,u_nm:1}, {name:"guest_sort", background:true});
}


function drop_all_collections(){
    var cols = db.getCollectionNames();
    var i = 0;
    for (; i < cols.length; i++) {
        var tmp = {drop: cols[i]};
        var rst = db.runCommand(tmp);
        if (1 == rst.ok) {
            print("info: success to drop " + cols[i]);
        } else {
            print("warning: fail to drop " + cols[i]);
        }
    }
}


function check_db(){
    var collections = db.getCollectionNames();
    if (collections.length > 0) {
        print("****************************************");
        print("warning: DB is not empty!");
        printjson(collections);
        print("warning: please confirm it!");
        print("****************************************");
        drop_all_collections();
        quit();
    }
}


conn = new Mongo(host_port);
db = conn.getDB(db_name);
db.auth(db_owner, db_passwd);
check_db();
quit();



